// ValidationAspects
// Written by Mike Saunders
// Released under Microsoft Public License (Ms-PL)
using System.Collections.Generic;
using System.Linq;
using ValidationAspects.Exceptions;
using ValidationAspects.Sdk;

namespace ValidationAspects.Core
{
	internal class CompoundValidatorFactory : IValidatorFactory
	{
		private readonly IEnumerable<IValidatorFactory> _factories;

		public CompoundValidatorFactory(IEnumerable<IValidatorFactory> factories)
		{
			Enforce.IsNotNull(factories, "factories");
			_factories = factories;
		}

		#region Implementation of IValidatorFactory
		public IValidator<T> Create<T>()
		{
			IValidator<T>[] validators = _factories.Select(f => f.Create<T>()).ToArray();

			return new Validator<T>((v, c) =>
			                        {
			                        	List<ValidationException> exceptions = new List<ValidationException>();

			                        	foreach (IValidator<T> validator in validators)
			                        	{
			                        		try
			                        		{
			                        			validator.Invoke(v, c);
			                        		}
			                        		catch (ValidationException e)
			                        		{
			                        			exceptions.Add(e);
			                        		}
			                        	}

			                        	if (exceptions.Count > 0)
			                        		throw new ValidationContextException(exceptions);
			                        });
		}
		#endregion
	}
}